#include "socktooler.h"

bool SockInit(){
    WORD sock_version = MAKEWORD(2,2);
    WSADATA data;
    if(WSAStartup(sock_version, &data))return false;
    return true;
}


int SockSendMsg(const char *msg, SOCKET sk){
    return send(sk, msg, sizeof(TransMsg),0);
}

int SockRecvMsg(char *msg,SOCKET sk){
    return recv(sk, msg, sizeof(TransMsg), 0);
}

void SockClose(SOCKET sk){
        closesocket(sk);
}

void SockDestory(){
    WSACleanup();
}

bool SockCreatConnection(int server_port, char* server_ipaddr, SOCKET &sk, sockaddr_in &sin){
    sk = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
    if(sk == INVALID_SOCKET)return false;
    sin.sin_family = AF_INET;
    sin.sin_port = htons(server_port);
    sin.sin_addr.S_un.S_addr = inet_addr(server_ipaddr);
    if(connect(sk,(sockaddr *) &sin,sizeof(sin)))return false;
    return true;
}

bool SockBindConnection(int client_port, SOCKET &sk, sockaddr_in &sin){
    sk =socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
    if(sk == INVALID_SOCKET)return false;
    sin.sin_family = AF_INET;
    sin.sin_port = htons(client_port);
    sin.sin_addr.S_un.S_addr = INADDR_ANY;
    if(bind(sk,(sockaddr *)&sin, sizeof(sin)) == SOCKET_ERROR)return false;
    if(listen(sk,MaxEstablishNum))return false;
    return true;
}
